package com.yonyou.crm.sys.org.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.rmitf.IUserRmService;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.enumeration.entity.OrgTypeEnum;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.CrmCodeConstant;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sys.org.entity.SysOrgVO;
import com.yonyou.crm.sys.org.rmitf.ISysOrgRmService;
import com.yonyou.iuap.context.InvocationInfoProxy;

@RestController
@RequestMapping(value = "/sys/orgs")
public class SysOrgCtrl {
	@Autowired
	private ISysOrgRmService service;
	@Autowired
	private IUserRmService userRmService;

	/**
	 * 组织列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */

	@RequestMapping( method = RequestMethod.GET)
	public Object queryPage(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
//
		@SuppressWarnings("unchecked")
		Map<String, Object> condMap = (Map<String, Object>) paramObj.get("searchMap");
		//本页面不进行分页查询，page参数在mapper中不使用
		Page<SysOrgVO> sysOrgPage = service.getPage(new Page<SysOrgVO>(0, 0), condMap);
		return ResponseUtil.getObject(sysOrgPage);


	}

	/**
	 * 新增组织
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping( method = RequestMethod.POST)
	public Object insert(HttpServletRequest request,
			HttpServletResponse response) {

		SysOrgVO sysOrg = RequestUtil.getVO(request, SysOrgVO.class);
		//部门下面不能建公司
		SysOrgVO fatherSysOrg = service.getDetail(sysOrg.getFatherorgId());
		if(fatherSysOrg.getOrgType()==OrgTypeEnum.DEPT.getValue()
				&&sysOrg.getOrgType()==OrgTypeEnum.COMPANY.getValue()){
			Map<String,Object> resultMap = new HashMap<String, Object>();
			resultMap.put(HttpKeyConstant.Code, CrmCodeConstant.ServerError);
			resultMap.put(HttpKeyConstant.Message, "部门下面不能新建公司");
			return resultMap;
		}
		//公司组织，可建立最多两级，集团--1级子公司--2级子公司
		String path=sysOrg.getPath();
		Integer orgType=sysOrg.getOrgType();
		if(orgType==OrgTypeEnum.COMPANY.getValue()&&path!=null){
			String [] pathLevel=path.split(",");
			if(pathLevel!=null&&pathLevel.length>2){
				Map<String,Object> resultMap = new HashMap<String, Object>();
				resultMap.put(HttpKeyConstant.Code, CrmCodeConstant.ServerError);
				resultMap.put(HttpKeyConstant.Message, "公司组织，最多建立2级");
				return resultMap;
			}
		}
		//部门组织，可建立最多5级
		if(orgType==OrgTypeEnum.DEPT.getValue()&&path!=null){
			String [] pathLevel=path.split(",");
			if(pathLevel!=null&&pathLevel.length>4){
				String id=pathLevel[pathLevel.length-5];
				fatherSysOrg = service.getDetail(Long.valueOf(id));
				if(fatherSysOrg.getOrgType()==OrgTypeEnum.DEPT.getValue()
						&&orgType==OrgTypeEnum.DEPT.getValue()){
					Map<String,Object> resultMap = new HashMap<String, Object>();
					resultMap.put(HttpKeyConstant.Code, CrmCodeConstant.ServerError);
					resultMap.put(HttpKeyConstant.Message, "部门组织，最多建立5级");
					return resultMap;
				}
			}
		}
		sysOrg = service.insert(sysOrg);
		SysOrgVO newSysOrg = service.getDetail(sysOrg.getId());
		return ResponseUtil.getObject(newSysOrg);
	}

	/**
	 * 组织详情
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException("id不能为空");
		}
		SysOrgVO sysOrg = service.getDetail(id);
		return ResponseUtil.getObject(sysOrg);
	}
	
	/**
	 * 批量删除组织
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idArray = paramObj.getString("ids");		

		if (idArray == null) {
			throw new CrmMessageException("ids参数为空");
		}
		
		String[] idStrs = idArray.split(",");
		
		@SuppressWarnings("unchecked")
		Map<String, Object> searchMap = (Map<String, Object>)paramObj.get("searchMap");

		int resType=service.batchDelete(idStrs);
		Page<SysOrgVO> orgPage = service.getPage(new Page<SysOrgVO>(0, 0), searchMap);
		if(resType==1)
			return ResponseUtil.getObject(orgPage, PCCodeConstant.Success,"数据删除成功");
		else
			return ResponseUtil.getObject(orgPage, PCCodeConstant.Info,"存在下级或关联业务单据，禁止删除");
	}
	/**
	 * 批量停启用组织
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "enable", method = RequestMethod.PUT)
	public Object batchUpdateEnableState(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException("ids参数为空");
		}
		String[] idArray = idsStr.split(",");
		if (idArray.length == 0) {
			throw new CrmMessageException("至少选中一条记录");
		}
		Integer enablestate = paramObj.getInt("enablestate");
		if (enablestate == null) {
        	throw new CrmMessageException("停启用状态不能为空");
		}

		String message = service.batchUpdateEnablestate(idArray, enablestate);
		@SuppressWarnings("unchecked")
		Page<SysOrgVO> orgPage = service.getPage(new Page<SysOrgVO>(0, 0), (Map<String, Object>)paramObj.get("searchMap"));

		return ResponseUtil.getObject(orgPage, PCCodeConstant.Success, message);
		
	}
	

	/**
	 * 修改组织
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		
		SysOrgVO sysOrg = RequestUtil.getVO(request, SysOrgVO.class);	

		if (sysOrg == null) {
			throw new CrmMessageException("id不能为空");
		}
		sysOrg.setId(id);
		service.update(sysOrg);
		sysOrg=service.getDetail(id);
		return ResponseUtil.getObject(sysOrg, PCCodeConstant.Success, null);
	}

	/**
	 * 组织树
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "/orgTree", method = RequestMethod.GET)
	public Object queryOrgTree(HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paraObj = RequestUtil.getParamObject(request);
		if (paraObj != null) {
			Integer type = (Integer)paraObj.get("type");
			Integer orgType = (Integer)paraObj.get("orgType");
			if(type!=null&&type== 1){
				Long id = new Long(InvocationInfoProxy.getParameter(LoginContextConstant.OrgId).toString());
				return fillOrgTree(service.getTreeByOrgType( OrgTypeEnum.GROUP.getValue(), null,id));
			}
			else if(type!=null&&type== 2){
				//系统初始化
				Long id = new Long(InvocationInfoProxy.getParameter(LoginContextConstant.UserId).toString());
				UserVO userVO=userRmService.detail(id);
				if(userVO.getType()<=2)
					return fillOrgTree(service.getTreeByOrgType(2, new Long(0),null));
				return fillOrgTree(service.getTreeByOrgType( OrgTypeEnum.COMPANY.getValue(), null,userVO.getOrgId()));
			}
			
			if (orgType != null) {
				
				if (orgType.intValue() != OrgTypeEnum.COMPANY.getValue() && orgType.intValue() != OrgTypeEnum.DEPT.getValue()) {
					throw new CrmMessageException("组织类型性错误");
				}
				Object fObj = paraObj.get("fatherorgId");
				Long fatherorgId = null;
				if (fObj == null) {
					if (orgType.intValue() == OrgTypeEnum.DEPT.getValue()) {
						//取登录人公司id
						fatherorgId = new Long(InvocationInfoProxy.getParameter(LoginContextConstant.OrgId).toString());
					}
				}
				else {
					fatherorgId = new Long(fObj.toString());
				}
				return fillOrgTree(service.getTreeByOrgType(orgType, fatherorgId,null));
			}
		}
		return fillOrgTree(service.getSysOrgTree());
	}
	
	private Object fillOrgTree(List<Map<String, Object>> orgList) {
		JSONObject result = new JSONObject();
		result.put("data", orgList);
		return ResponseUtil.getObject(result);
	}
}
